package com.sakura.probe.controller.admin;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sakura.probe.common.api.CommonResult;
import com.sakura.probe.common.util.JwtTokenUtil;
import com.sakura.probe.nosql.redis.RedisKey;
import com.sakura.probe.nosql.redis.RedisService;
import com.sakura.probe.pojo.PersonInfo;
import com.sakura.probe.service.PersonInfoService;
import com.sakura.probe.service.TopicCategoryService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

@Api(tags = "LoginController",description = "后台管理的相关操作")
@Controller
@Slf4j
@RequestMapping("/backstage")
public class AdminLoginController {
    @Autowired
    private PersonInfoService personService;
    @Autowired
    private TopicCategoryService topicCategoryService;
    @Autowired
    private RedisService redisService;

    @ApiOperation("后台登录")
    @GetMapping("/login")
    @ResponseBody
    public CommonResult login(String account,String password){
        log.info("parm is = "+account+":"+password);
        PersonInfo person = personService.getOne(new QueryWrapper<PersonInfo>().eq("phone", account)
                .or().eq("mail", account));
        if (null==person){
            return CommonResult.failed("账号错误");
        }else if (!(person.getPassword()).equals(SecureUtil.md5(password))){
            return CommonResult.failed("密码错误");
        }else if (person.getRole()!=null&&person.getRole()==0){
            return CommonResult.failed("权限不够,只有管理员才可登录");
        }
        //将用户信息存储在redis中并设置存活时间为12h
        redisService.set(RedisKey.getPersonInfo()+person.getUserId(), JSONUtil.toJsonStr(person),60*60*12);
        //登录成功后返回生成的token给前台页面
        return CommonResult.success(JwtTokenUtil.createToken(String.valueOf(person.getUserId())));
    }

    /**
     * 1) 统计各个帖子类型占的比例重量
     * 2) 统计前7天用户的注册量
     * @return
     */
    @ApiOperation("后台相关数据的统计页面")
    @GetMapping("/staticData")
    @ResponseBody
    public Map<String,Object> statisticData(){
        Map<String,Object> modelMap = new HashMap<>();
        personService.getPersonStaticData(modelMap);
        topicCategoryService.getTopicStaticData(modelMap);
        return modelMap;
    }







}
